/*
 * Copyright (c) 2019.  武汉中科图灵科技有限公司
 * Date :  2019/1/5
 * Author ：F12 Console=> atob("MzMxNDkxODAwQHFxLmNvbQ==")
 * Version ：1.6.2
 */

import {
  loginByUsername,
  logout,
  getInfo,
  getMenus, //api/admin/user/front/menus
  isSuperAdmin
} from '@/api/login'
import {
  Message
} from 'element-ui'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'

const user = {
  state: {
    user: '',
    userId: '',
    status: '',
    code: '',
    token: getToken(),
    name: '',
    username: '',
    site: '',
    tenantNo: '',
    avatar: '',
    introduction: '',
    adminid: '',
    roles: [],
    menus: undefined,
    eleemnts: undefined,
    permissionMenus: undefined,
    issuperadmin: false,
    setting: {
      articlePlatform: []
    }
  },

  mutations: {
    SET_CODE: (state, code) => {
      state.code = code
    },
    SET_USERID: (state, userId) => {
      state.userId = userId
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_MENUS: (state, menus) => {
      state.menus = menus
    },
    SET_ELEMENTS: (state, elements) => {
      state.elements = elements
    },
    LOGIN_SUCCESS: () => {
      console.log('login success')
    },
    LOGOUT_USER: state => {
      state.user = ''
    },
    SET_PERMISSION_MENUS: (state, permissionMenus) => {
      state.permissionMenus = permissionMenus
    },
    SET_ADMIN_ID: (state, id) => {
      state.adminid = id
    },
    SET_USERNAME: (state, username) => {
      state.username = username;
    },
    SET_SITE: (state, site) => {
      state.site = site;
    },
    SET_TENANTNO: (state, tenantNo) => {
      state.tenantNo = tenantNo;
    },
    SET_SUPER_ADMIN: (state, auth) => {
      state.issuperadmin = auth;
    }
  },

  actions: {
    // 用户名登录
    LoginByUsername({
      commit
    }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        loginByUsername(username, userInfo.password, userInfo.code, userInfo.image).then(response => {
          const data = response
          if (data.access_token === '' || data.access_token === undefined) {
            Message({
              message:data.message,
              type: 'warning'
            })
            return Promise.reject('error')
          } else {
            const token = 'Bearer ' + data.access_token;
            setToken(token)
            commit('SET_TOKEN', token);
            commit('SET_USERID', data.userId)
            resolve()
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({
      commit
    }) {
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          const data = response;
          commit('SET_ADMIN_ID', data.id)
          commit('SET_ROLES', 'admin')
          commit('SET_NAME', data.name)
          commit('SET_USERNAME', data.username)
          commit('SET_SITE', data.site)
          commit('SET_TENANTNO', data.tenantNo)
          commit('SET_AVATAR', 'http://file.tmc.turing.ac.cn/firecontrol_user.png')
          commit('SET_INTRODUCTION', data.description)
          const menus = {}
          for (let i = 0; i < data.menus.length; i++) {
            menus[data.menus[i].code] = true
          }
          commit('SET_MENUS', menus)
          const elements = {}
          for (let i = 0; i < data.elements.length; i++) {
            elements[data.elements[i].code] = true
          }
          commit('SET_ELEMENTS', elements);
          isSuperAdmin({
            userId: data.id
          }).then(res => {
            commit('SET_SUPER_ADMIN', res)
          })
          resolve(response)
        }).catch(error => {
          reject(error)
        })
        getMenus().then(response => {
          commit('SET_PERMISSION_MENUS', response)
        });
      })
    },

    // 第三方验证登录
    // LoginByThirdparty({ commit, state }, code) {
    //   return new Promise((resolve, reject) => {
    //     commit('SET_CODE', code)
    //     loginByThirdparty(state.status, state.email, state.code).then(response => {
    //       commit('SET_TOKEN', response.data.token)
    //       setToken(response.data.token)
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },

    // 登出
    LogOut({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        const token = state.token
        commit('SET_TOKEN', '')
        logout(token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_MENUS', undefined)
          commit('SET_ELEMENTS', undefined)
          commit('SET_PERMISSION_MENUS', undefined)
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({
      commit
    }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_MENUS', undefined)
        commit('SET_ELEMENTS', undefined)
        commit('SET_PERMISSION_MENUS', undefined)
        removeToken()
        resolve()
      })
    }
  }
}

export default user
